package com.qfedu.websocket;


import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/webSocket/{oid}")//webSocket请求路径
public class WebSocketServer {

    private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();


    /** 前端发送请求建立websocket请求会进入 @onOpen **/
    @OnOpen
    public void open(@PathParam("oid") String orderId,Session session){
        sessionMap.put(orderId,session);
    }
    /** 前端关闭页面或主动关闭websocket连接，都会执行 **/
    @OnClose
    public void close(@PathParam("oid")String orderId){
        sessionMap.remove(orderId);
    }

    public static void sndMsg(String orderId,String msg){
        try {
            Session session = sessionMap.get(orderId);
            session.getBasicRemote().sendText(msg);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
